﻿#region License

// Another free, open solution by folks who get it.
// Copyright © 2011 Business in Unison, Inc.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Patterns.Text
{
	/// <summary>
	/// 	Defines ease-of-use extensions for regular expressions.
	/// </summary>
	public static class RegexExtensions
	{
		/// <summary>
		/// Compiles the specified pattern.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <returns></returns>
		public static CompiledRegex Compiled(this Regex pattern)
		{
			return new CompiledRegex(pattern.ToString(), pattern.Options);
		}

		/// <summary>
		/// Returns the expression's first match as a dictionary.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="input">The input.</param>
		/// <returns></returns>
		public static IDictionary<string, string> DictionaryMatch(this Regex pattern, string input)
		{
			Match match = pattern.Match(input);
			return MatchToDictionary(pattern, match);
		}

		/// <summary>
		/// Returns each of the expression's matches as a dictionary.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="input">The input.</param>
		/// <returns></returns>
		public static IEnumerable<IDictionary<string, string>> DictionaryMatches(this Regex pattern, string input)
		{
			IEnumerable<Match> matches = pattern.Matches(input).OfType<Match>();
			return matches.Select(match => MatchToDictionary(pattern, match));
		}

		/// <summary>
		/// Extracts the group.
		/// </summary>
		/// <param name="pattern">The pattern.</param>
		/// <param name="groupName">Name of the group.</param>
		/// <param name="input">The input.</param>
		/// <returns></returns>
		public static string ExtractGroup(this Regex pattern, string groupName, string input)
		{
			IDictionary<string, string> values = pattern.DictionaryMatch(input);
			return values.ContainsKey(groupName) ? values[groupName] : null;
		}

		private static IDictionary<string, string> MatchToDictionary(Regex pattern, Match match)
		{
			return pattern.GetGroupNames().ToDictionary(name => name, name => match.Groups[name].Value);
		}
	}
}